package top.soulblack.purchasesale.controller.setting;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.soulblack.purchasesale.common.Result;
import top.soulblack.purchasesale.model.Goods;
import top.soulblack.purchasesale.service.GoodsService;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static top.soulblack.purchasesale.common.CodeMsg.*;

/**
 * create by 小川
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @ResponseBody
    @RequestMapping("/addGoods")
    public Result<Boolean> addGoods(String goods) {

        List<Goods> good = JSON.parseArray(goods,Goods.class);
        for(Goods value:good){
            //判断排序数是否在1到100区间
            //System.out.println(goods.getColor());
            if (value.getSort() > 100 || value.getSort() < 1) {
                return Result.error(SORT_ERROR);
            }
            if(goodsService.exist(value)){
                GOODS_BAR.setMsg("商品条码重复："+value.getBarCode()+";");
                return Result.error(GOODS_BAR);
            }
            if(goodsService.exist_single(value)){
                GOODS_BAR.setMsg("单品条码重复："+value.getOnlyBarCode()+";");
                return Result.error(GOODS_BAR);
            }
        }
        for(Goods value:good){
            goodsService.addGoods(value);
        }
        return Result.success(true);
    }

    @ResponseBody
    @RequestMapping("/editGoods")
    public Result<Boolean> editGoods(Goods goods){
        if(goodsService.updateGoods(goods)){
            return Result.success(true);
        }
        return Result.error(GOODS_UPDATE);
    }

    @RequestMapping("/deleteGoods")
    @ResponseBody
    // 后期需要加上User权限验证，否则暴露接口有危险。
    public Result<Boolean> deleteGoods(String goodsName) {
        if (goodsService.deleteGoods(goodsName)) {
            return Result.success(true);
        }
        return Result.error(GOODS_DELETE);
    }

}
